package com.tian.system.controller;

import com.tian.common.core.domain.AjaxResult;
import com.tian.system.common.security.SecurityCommon;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.representations.AccessToken;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/login")
public class LoginController {

    /**
     * 根据token令牌获取用户sessionid
     *
     * @param request
     * @return
     */
    @RequestMapping("/tokenlogin")
    @ResponseBody
    public String tokenLogin(HttpServletRequest request) {
        Map<String,String> map =new HashMap<String,String>();
        AjaxResult ajaxResult = new AjaxResult();
        String session_id = request.getSession().getId();
        map.put("sessionid",session_id);
        String result = ajaxResult.success("登录成功", map);
        return result;
    }
    /**
     * 根据token令牌获取用户sessionid
     *
     * @param request
     * @return
     */
    @RequestMapping("/getsessionid")
    @ResponseBody
    public String getSessionId(HttpServletRequest request) {
        Map<String,String> map =new HashMap<String,String>();
        AjaxResult ajaxResult = new AjaxResult();
        String session_id = request.getSession().getId();
        map.put("sessionid",session_id);
        String result = ajaxResult.success("操作成功", map);
        return result;
    }
    private AccessToken getAccessToken(KeycloakAuthenticationToken principal) {
        KeycloakAuthenticationToken token = principal;
        KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) token.getPrincipal();
        KeycloakSecurityContext context = keycloakPrincipal.getKeycloakSecurityContext();
        return context.getToken();
    }
    @RequestMapping("/login")
    @PreAuthorize("hasAnyAuthority ('aa:bb:cc')")
    @ResponseBody
    public String ajaxLogin() {
        SecurityCommon securityCommon = new SecurityCommon();
        securityCommon.getUser();
        return "";
    }
}
